//
//  PartyKnowledgeController.m
//  UESTCPioneer
//
//  Created by Apple on 14-9-25.
//  Copyright (c) 2014年 Sway. All rights reserved.
//

#import "PartyKnowledgeController.h"
#import "MBProgressHUD.h"
#import "PartyVirtualTestEntity.h"
#import "PartyTestResultController.h"

@interface PartyKnowledgeController ()
{
    UIScrollView * _scrollView;
    UIView * _answerView;
    UIButton * _resultBtn;
    UITextView * _answerTextView;
    UITextView * _questionTextView;
    UIButton * _rightBtn;
    UIButton * _errorBtn;
    UIButton * _nextBtn;
    UIView * _questionView;
    MBProgressHUD * HUD;
    NSMutableArray * _dataArray;
    NSInteger _no;
    NSString * _answerText;
    NSInteger _totalScore;
    UIButton * _titleNoBtn;
    BOOL _isReturn;
}
@end

@implementation PartyKnowledgeController

-(void)getServerData{
    
    //显示指示器
    MBProgressHUD * hud  = [MBProgressHUD showHUDAddedTo:self.view.window animated:YES];
    hud.labelText = @"考题加载中";
    hud.labelFont = [UIFont systemFontOfSize:15];
    hud.dimBackground = YES;
    
    [NetworkCenter RKRequestWithData:@{@"type":@"getFalse"} EntityName:@"PartyVirtualTestEntity" Mapping:[Mapping PartyVirtualTestEntityMapping] SuccessBlock:^(NSArray *resultArray) {
        //
        //        NSMutableArray *newArray = [[NSMutableArray alloc]init];
        //        [newArray addObjectsFromArray:_dataArray];
        //        [newArray addObjectsFromArray:resultArray];
        //        NSArray *result = [[NSArray alloc]initWithArray:newArray];
        _dataArray = [NSMutableArray arrayWithArray:resultArray];
        
        [self setQuestionText];
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
        
    } failure:^(NSError *error) {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络较差，考题加载失败，是否重新加载?" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        
        [alert show];
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
    }];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //1.设置问题View
    [self setQuestionView];
    
    //2.设置解析View
    //    [self setAnswerView];
    [self setNextButton];
    //    _answerView.hidden = YES;
    self.title = @"党识竞答";
    _isReturn = NO;
    _no = 0;
    [self getServerData];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _no = 0;
    _totalScore = 0;
    if (_isReturn) {
        [_dataArray removeAllObjects];
        [self getServerData];
    }
}
-(void)setQuestionView{
    
    CGFloat w = self.view.frame.size.width;
    CGFloat sh = self.view.frame.size.height;
    UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
    scrollView.contentSize = CGSizeMake(w, sh);
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.backgroundColor = [UIColor colorWithRed:232.0f/255.0f green:233.0f/255.0f blue:232.0f/255.0f alpha:1];
    _scrollView = scrollView;
    
    //1.设置UI
    UIView * questionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, w, 400)];
    [scrollView addSubview:questionView];
    _questionView  = questionView;
    CGFloat x = (w - 150) / 2;
    
    //1.1 题号
    UIButton * titleNoBtn = [[UIButton alloc] initWithFrame:CGRectMake(x - 5, 10, 150, 40)];
    [titleNoBtn setTitleEdgeInsets:UIEdgeInsetsMake(20, 5, 0, 0)];
    titleNoBtn.contentMode = UIViewContentModeScaleAspectFit;
    [titleNoBtn setBackgroundImage:[UIImage imageNamed:@"flag.png"] forState:UIControlStateNormal];
    [titleNoBtn setBackgroundImage:[UIImage imageNamed:@"flag.png"] forState:UIControlStateHighlighted];
    [titleNoBtn.titleLabel setFont:[UIFont systemFontOfSize:16.0f]];
    [questionView addSubview:titleNoBtn];
    _titleNoBtn = titleNoBtn;
    
    [self.view addSubview:scrollView];
    
    //1.2 题目
    CGFloat y = CGRectGetMaxY(titleNoBtn.frame);
    UITextView * questionTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, y , w - 20, 220)];
    [questionTextView setEditable:NO];
    questionTextView.font = [UIFont systemFontOfSize:16.0f];
    _questionTextView = questionTextView;
    
    [questionView addSubview:questionTextView];
    
    CGFloat btnY = CGRectGetMaxY(questionTextView.frame) + 10;
    CGFloat btnX = (w - 20 - 100);
    //1.3 选择按钮
    UIButton * rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(20,btnY,100, 30)];
    rightBtn.tag = 0;
    
    [rightBtn setBackgroundColor:[UIColor colorWithRed:222.0f/255.0f green:250.0f/255.0f blue:201.0f/255.0f alpha:1.0f]];
    
    [rightBtn setTitleColor:[UIColor colorWithRed:176.0f/255.0f green:37.0f/255.0f blue:33.0f/255.0f alpha:1.0f] forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor colorWithRed:176.0f/255.0f green:37.0f/255.0f blue:33.0f/255.0f alpha:1.0f] forState:UIControlStateHighlighted];
    [rightBtn setTitle:@"正确" forState:UIControlStateNormal];
    [rightBtn setTitle:@"正确" forState:UIControlStateHighlighted];
    [rightBtn addTarget:self action:@selector(returnResult:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton * errorBtn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, 100, 30)];
    [errorBtn setBackgroundColor:[UIColor colorWithRed:176.0f/255.0f green:37.0f/255.0f blue:33.0f/255.0f alpha:1.0f]];
    [errorBtn setTitle:@"错误" forState:UIControlStateNormal];
    [errorBtn setTitle:@"错误" forState:UIControlStateHighlighted];
    errorBtn.tag = 1;
    [errorBtn addTarget:self action:@selector(returnResult:) forControlEvents:UIControlEventTouchUpInside];
    
    [questionView addSubview:rightBtn];
    [questionView addSubview:errorBtn];
    _rightBtn = rightBtn;
    _errorBtn = errorBtn;
    
    [_rightBtn.layer setCornerRadius:5];
    [_rightBtn.layer setBorderWidth:1];
    [_rightBtn.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];
    
    [_errorBtn.layer setCornerRadius:5];
    [_errorBtn.layer setBorderWidth:1];
    [_errorBtn.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];
    
    /* 以前的提示方式
    CGFloat labelX = (questionTextView.frame.size.width - 85);
    CGFloat labelY = (questionTextView.frame.size.height - 35);
    
    //1.4 result标志
    UIButton * resultBtn= [[UIButton alloc] initWithFrame:CGRectMake(labelX, labelY, 80, 30)];
    [questionTextView addSubview:resultBtn];
    _resultBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    _resultBtn = resultBtn;
    */
    CGFloat labelX = (questionTextView.frame.size.width - 59);
    CGFloat labelY = (questionTextView.frame.size.height - 49);
    //1.4 result标志
    UIButton * resultLbl = [[UIButton alloc] initWithFrame:CGRectMake(labelX, labelY, 45, 45)];
    
    [questionTextView addSubview:resultLbl];
    _resultBtn = resultLbl;
}

-(void)setAnswerView{
    
    CGFloat w = self.view.frame.size.width;
    //1.设置UI
    UIView * answerView = [[UIView alloc] initWithFrame:CGRectMake(0, 300, w, 320)];
    [_scrollView addSubview:answerView];
    _answerView = answerView;
    
    CGFloat x = (w - 120) / 2;
    
    //1.1 题号
    UIButton * titleNoBtn = [[UIButton alloc] initWithFrame:CGRectMake(x , 10, 120, 60)];
    [titleNoBtn setBackgroundImage:[UIImage imageNamed:@"flag.png"] forState:UIControlStateNormal];
    [titleNoBtn setBackgroundImage:[UIImage imageNamed:@"flag.png"] forState:UIControlStateHighlighted];
    
    [answerView addSubview:titleNoBtn];
    [self.view addSubview:_scrollView];
    
    //1.2 题目
    CGFloat y = CGRectGetMaxY(titleNoBtn.frame);
    UITextView * answerTextView = [[UITextView alloc] initWithFrame:CGRectMake(10, y , w - 20, 180)];
    [answerTextView setEditable:NO];
    answerTextView.font = [UIFont systemFontOfSize:16.0f];
    [answerView addSubview:answerTextView];
    _answerTextView = answerTextView;
    
    //1.3 Next按钮
    CGFloat btnY = CGRectGetMaxY(answerTextView.frame) + 20;
    CGFloat btnX = (self.view.frame.size.width - 120)/2;
    UIButton * nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, 120, 30)];
    [nextBtn addTarget:self action:@selector(nextQuestion:) forControlEvents:UIControlEventTouchUpInside];
//    [nextBtn setBackgroundImage:[UIImage imageNamed:@"background.png"] forState:UIControlStateNormal];
//    [nextBtn setBackgroundImage:[UIImage imageNamed:@"background.png"] forState:UIControlStateHighlighted];
    [nextBtn setBackgroundColor:[UIColor colorWithRed:176.0f/255.0f green:37.0f/255.0f blue:33.0f/255.0f alpha:1.0f]];
    [nextBtn.layer setCornerRadius:5];
    [nextBtn.layer setBorderWidth:1];
    [nextBtn.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];
    [nextBtn setTitle:@"下一题" forState:UIControlStateNormal];
    [nextBtn setTitle:@"下一题" forState:UIControlStateHighlighted];
    [answerView addSubview:nextBtn];
}

-(void)setNextButton{
    //1 Next按钮
    CGFloat btnY = CGRectGetMaxY(_questionTextView.frame) + 20;
    CGFloat btnX = (self.view.frame.size.width - 180)/2;
    UIButton * nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, 180, 30)];
    [nextBtn addTarget:self action:@selector(nextQuestion:) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn setBackgroundColor:[UIColor colorWithRed:176.0f/255.0f green:37.0f/255.0f blue:33.0f/255.0f alpha:1.0f]];
    [nextBtn.layer setCornerRadius:5];
    [nextBtn.layer setBorderWidth:1];
    [nextBtn.layer setBorderColor:[UIColor colorWithWhite:146.0/255.0 alpha:0.5].CGColor];

    [nextBtn setTitle:@"下一题" forState:UIControlStateNormal];
    [nextBtn setTitle:@"下一题" forState:UIControlStateHighlighted];
    [_questionView addSubview:nextBtn];
    _nextBtn = nextBtn;
    [_nextBtn.layer setCornerRadius:5];
    _nextBtn.hidden = YES;
}

-(void)returnResult:(UIButton *)btn{
    
    if (_dataArray.count == 0) {
        [Alert showAlert:@"网络连接失败!"];
        return;
    }
    
    _rightBtn.hidden = YES;
    _errorBtn.hidden = YES;
    _nextBtn.hidden = NO;
    
    //判断是否答对
    [self checkResult:btn.tag];
    /*
     _answerView.hidden = NO;
     CGFloat pointY = _scrollView.contentSize.height - self.view.frame.size.height;
     [UIView beginAnimations:@"Curl"context:nil];//动画开始
     [UIView setAnimationDuration:0.5];
     [UIView setAnimationDelegate:self];
     [_scrollView setContentOffset:CGPointMake(0, pointY)];
     [UIView commitAnimations];
     */
}

-(void)nextQuestion:(UIButton*)btn{
    NSLog(@"_no = %i",_no);
    _rightBtn.hidden = NO;
    _errorBtn.hidden = NO;
    _nextBtn.hidden = YES;
    if (_no == _dataArray.count - 1) {
        [self sendAndShowResult];
    } else {
        NSLog(@"下一题");
        _no ++;
        [self setQuestionText];
    }
    
    /*
     _answerView.hidden = YES;
     [UIView beginAnimations:@"Curl"context:nil];//动画开始
     [UIView setAnimationDuration:0.5];
     [UIView setAnimationDelegate:self];
     [_scrollView setContentOffset:CGPointMake(0, 0)];
     [UIView commitAnimations];
     */
}

#pragma mark -判断选择正误
-(void)checkResult:(NSInteger) result{
    _resultBtn.hidden = NO;
    if (result == 0) {
        //选择了正确按钮
        _answerText = @"对";
    } else if (result == 1){
        //选择了错误按钮
        _answerText = @"错";
    }
    
    PartyVirtualTestEntity * entity = _dataArray[_no];
    if ([_answerText isEqualToString:entity.answer]) {
        [Alert showAlert:@"您答对了!"];
        [_resultBtn setBackgroundImage:[UIImage imageNamed:@"yes.png"] forState:UIControlStateNormal];
//        [_resultBtn setTitle:@"答案:正确" forState:UIControlStateNormal];
        _totalScore ++;
    } else {
        [Alert showAlert:@"您答错了!"];
        [_resultBtn setBackgroundImage:[UIImage imageNamed:@"no.png"] forState:UIControlStateNormal];
//        [_resultBtn setTitle:@"答案:错误" forState:UIControlStateNormal];
    }
    [_resultBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
}

-(void)setQuestionText{
    NSLog(@"设置标题:_no = %i",_no + 1);
    [_titleNoBtn setTitle:[NSString stringWithFormat:@"判断题 [%i/%i]",_no + 1,_dataArray.count] forState:UIControlStateNormal];
    PartyVirtualTestEntity * entity = _dataArray[_no];
    
    NSLog(@"***********_no = %i********",_no);
    _questionTextView.text = entity.content;
    _resultBtn.hidden = YES;
}

#pragma mark - 计算并显示成绩
-(void)sendAndShowResult{
    _isReturn = YES;
    //1.向后台发送成绩
    //http://115.28.239.113:8080/ScienceApp/AdminRecord.do?type=dangshiExam&userName=&userId=&score=
    //http://115.28.239.113:8080/ScienceApp/AdminRecord.do ? type=dangshiExam&userName=&userId=&score=
    NSDictionary *requestData=@{@"type":@"dangshiExam"
                                ,@"userId":[constant getUserId]
                                ,@"userName":[constant getUserName]
                                ,@"score":[NSString stringWithFormat:@"%i",_totalScore]
                                };
    
    NSLog(@"党史竞答：requestData = %@",requestData);
    [NetworkCenter AFRequestWithRecordData:requestData SuccessBlock:^(AFHTTPRequestOperation *operation, id resultObject) {
//        NSArray *arr = [NSJSONSerialization JSONObjectWithData:resultObject options:NSJSONReadingMutableLeaves error:nil];
//        NSDictionary *dic =arr[0];
//        NSLog(@"返回值dic = %@",dic);
//        if ([dic[@"result"] isEqualToString:@"success"]){
//            [Alert showAlert:@"上传成功"];
//        } else {
//        }
    } FailureBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [Alert showAlert:@"网络连接出错"];
        NSLog(@"网络连接出错 = %@",error.localizedDescription);
    }];
    
    
    //2.显示成绩
    NSString * name = [NSString stringWithFormat:@"%@同志:",[constant getName] ];
    NSString * text = [NSString stringWithFormat:@"   在本次党的知识竞赛中答对了%i道题.",_totalScore];
    
    PartyTestResultController * controller = [[PartyTestResultController alloc] initWithName:name result:text integral:@""];
    [self.navigationController pushViewController:controller animated:YES];
}
#pragma mark UIAlertView代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        [self getServerData];
    } else{
        [MBProgressHUD hideAllHUDsForView:self.view.window animated:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
@end
